<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Ruby Exceptions</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="Ruby Exceptions" />
<meta name="keywords" content="ruby exceptions,ruby rescue,ruby begin rescue,ruby raise" />
<meta name="Distribution" content="Global" />
<meta name="author" content="Satish Talim / Original design: Erwin Aligam - ealigam@gmail.com" />
<meta name="copyright" content="Satish Talim 2007 and beyond..." />
<meta name="verify-v1" content="rFu86se+IkbtF+bH8mgJBKwU5HnKaSd8Ghw9umXQOkM=" />
<meta name="robots" content="index,follow" />
<meta http-equiv="Expires" content="0" />
<meta name="revisit-after" content="1 days" />
<link rel="stylesheet" href="/images/NewOrange.css" type="text/css" />
<link rel="stylesheet" href="/images/syntaxhighlighter.css" type="text/css" />
<link rel="icon" type="image/ico" href="/images/favicon.ico" />
<link href="https://plus.google.com/104011292189143717925/" rel="publisher" />
<!-- Google +1 button code -->
<link rel="canonical" href="/satishtalim/ruby_exceptions.html" />
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>

<!-- Google Analytics code -->
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-59044-10']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
<!-- Google Analytics code ends -->
</head>

<body>
<!-- wrap starts here -->
<div id="wrap">

    <div id="header">

        <h1 id="logo">Ruby<span class="orange">Learning.github.io</span></h1>
        <h2 id="slogan">Helping Ruby Programmers become Awesome!</h2>

    </div>

    <div id="menu">
        <ul>
            <li><a href="/" title="Home page for rubylearning.github.io">Home</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Get started Learning Ruby here...">Tutorial</a></li>
            <li><a href="/download/downloads.html" title="Download this tutorial as an eBook">Downloads</a></li>
            <li><a href="/other/testimonials.html" title="People around the world who benefited from this site">Testimonials</a></li>
            <li><a href="/other/certification.html" title="Get certified in Ruby">Certification</a></li>
            <li><a href="/satishtalim/ruby_guide.html" title="Ruby Guide, Mentor">Mentor</a></li>
            <li><a href="https://blog.rubylearning.github.io/" title="Ruby blog of Learning Ruby site">Blog</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Online Ruby Course">Online Course</a></li>
            <li><a href="http://ruby-challenge.rubylearning.github.io/" title="Ruby Programming Challenge for Newbies">Challenge</a></li>
            <li><a href="/satishtalim/about.html" title="Information about Satish Talim">About</a></li>
        </ul>
    </div>

    <!-- content-wrap starts here -->
    <div id="content-wrap">

            <div id="main">

                <div id="main-inner"><a name="TemplateInfo"></a>
                <h1>Ruby Exceptions</h1>

                <p class="post-footer align-right">
                  <strong>
                    <a href="/satishtalim/ruby_access_control.html">&lt;Access Control | </a>
                    <a href="/satishtalim/tutorial.html">TOC | </a>
                    <a href="/satishtalim/ruby_logging.html">Logging &gt;</a>
                  </strong>
                </p>

                <h3>Raising An Exception</h3>

                <p>An <em>exception</em> is a special kind of object, an instance of the class <strong>Exception</strong> or a descendant of that class that represents some kind of exceptional condition; it indicates that something has gone wrong. When this occurs, an exception is raised (or thrown). By default, Ruby programs terminate when an exception occurs. But it is possible to declare exception handlers. An exception handler is a block of code that is executed if an exception occurs during the execution of some other block of code. <em>Raising</em> an exception means stopping normal execution of the program and transferring the flow-of-control to the exception handling code where you either deal with the problem that's been encountered or exit the program completely. Which of these happens - dealing with it or aborting the program - depends on whether you have provided a <strong>rescue</strong> clause (<strong>rescue</strong> is a fundamental part of the Ruby language). If you haven't provided such a clause, the program terminates; if you have, control flows to the <strong>rescue</strong> clause.</p>

                <p>Ruby has some predefined classes - <strong><a href="http://ruby-doc.org/core-2.3.0/Exception.html">Exception</a></strong> and its children - that help you to handle errors that can occur in your program. The following figure shows the Ruby exception hierarchy.</p>

                <p><a href="/images/exception.jpg" title="Exception Hierarchy"><img src="/images/exception.jpg" alt="Exception Hierarchy" /></a></p>

                <p><strong>Reference</strong>: The above figure is from the <em>Programming Ruby</em> book.</p>

                <p>The chart above shows that most of the subclasses extend a class known as <strong>StandardError</strong>. These are the "normal" exceptions that typical Ruby programs try to handle. The other exceptions represent lower-level, more serious, or less recoverable conditions, and normal Ruby programs do not typically attempt to handle them.</p>

                <p>The following method raises an exception whenever it's called. Its second message will never be printed. Program <strong>p043raise.rb</strong></p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p043raise.rb
                def raise_exception
                  puts 'I am before the raise.'
                  raise 'An error has occured'
                  puts 'I am after the raise'
                end
                raise_exception
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The output is:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                >ruby p043raise.rb
                I am before the raise.
                p043raise.rb:4:in `raise_exception': An error has occured (RuntimeError)
                    from p043raise.rb:7
                >Exit code: 1
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The <strong>raise</strong> method is from the <strong>Kernel</strong> module. By default, <strong>raise</strong> creates an exception of the <strong>RuntimeError</strong> class. To raise an exception of a specific class, you can pass in the class name as an argument to <strong>raise</strong>. Refer program <strong>p044inverse.rb</strong></p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p044inverse.rb
                def inverse(x)
                  raise ArgumentError, 'Argument is not numeric' unless x.is_a? Numeric
                  1.0 / x
                end
                puts inverse(2)
                puts inverse('not a number')
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The output is:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                >ruby p044inverse.rb
                0.5
                p044inverse.rb:3:in `inverse': Argument is not numeric (ArgumentError)
                    from p044inverse.rb:7
                >Exit code: 1
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>Remember, methods that act as queries are often named with a trailing ?. <strong>is_a?</strong> is a method in the <strong>Object</strong> class and returns true or false. The <strong>unless</strong> modifier when tacked at the end of a normal statement means execute the preceding expression unless condition is true.</p>

                <p><strong>Defining new exception classes</strong>: To be even more specific about an error, you can define your own <strong>Exception</strong> subclass:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                class NotInvertibleError &lt; StandardError
                end
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <h3>Handling an Exception</h3>

                <p>To do exception handling, we enclose the code that could raise an exception in a <strong>begin-end</strong> block and use one or more <strong>rescue</strong> clauses to tell Ruby the types of exceptions we want to handle. It is to be noted that the body of a method definition is an implicit <strong>begin-end</strong> block; the <strong>begin</strong> is omitted, and the entire body of the method is subject to exception handling, ending with the <strong>end</strong> of the method.</p>

                <p>The program <strong>p045handexcp.rb</strong> illustrates this:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p045handexcp.rb
                def raise_and_rescue
                  begin
                    puts 'I am before the raise.'
                    raise 'An error has occured.'
                    puts 'I am after the raise.'
                  rescue
                    puts 'I am rescued.'
                  end
                  puts 'I am after the begin block.'
                end
                raise_and_rescue
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The output is:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                >ruby p045handexcp.rb
                I am before the raise.
                I am rescued.
                I am after the begin block.
                >Exit code: 0
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>Observe that the code interrupted by the exception never gets run. Once the exception is handled, execution continues immediately after the <strong>begin</strong> block that spawned it.</p>

                <p>If you write a <strong>rescue</strong> clause with no parameter list, the parameter defaults to <strong>StandardError</strong>. Each <strong>rescue</strong> clause can specify multiple exceptions to catch. At the end of each <strong>rescue</strong> clause you can give Ruby the name of a local variable to receive the matched exception. The parameters to the <strong>rescue</strong> clause can also be arbitrary expressions (including method calls) that return an <strong>Exception</strong> class. If we use <strong>raise</strong> with no parameters, it re-raises the exception.</p>

                <p>You can stack <strong>rescue</strong> clauses in a begin/rescue block. Exceptions not handled by one <strong>rescue</strong> clause will trickle down to the next:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                begin
                  # -
                rescue OneTypeOfException
                  # -
                rescue AnotherTypeOfException
                  # -
                else
                  # No exceptions
                end
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>For each <strong>rescue</strong> clause in the <strong>begin</strong> block, Ruby compares the raised Exception against each of the parameters in turn. The match will succeed if the exception named in the <strong>rescue</strong> clause is the same as the type of the currently thrown exception, or is a superclass of that exception. The code in an <strong>else</strong> clause is executed if the code in the body of the <strong>begin</strong> statement runs to completion <em>without</em> exceptions. If an exception occurs, then the <strong>else</strong> clause will obviously not be executed. The use of an <strong>else</strong> clause is not particularly common in Ruby.</p>

                <p>If you want to interrogate a rescued exception, you can map the Exception (we are using the Exception <strong>StandardError</strong> below) object to a variable within the <strong>rescue</strong> clause, as shown in the program <strong>p046excpvar.rb</strong></p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p046excpvar.rb
                begin
                  raise 'A test exception.'
                rescue StandardError => e
                  puts e.message
                  puts e.backtrace.inspect
                end
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The output is:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                >ruby p046excpvar.rb
                A test exception.
                ["p046excpvar.rb:3"]
                >Exit code: 0
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The <strong>Exception</strong> class defines two methods that return details about the exception. The <strong>message</strong> method returns a string that may provide human-readable details about what went wrong. The other important method is <strong>backtrace</strong>. This method returns an array of strings that represent the call stack at the point that the exception was raised.</p>

                <p>If you need the guarantee that some processing is done at the end of a block of code, regardless of whether an exception was raised then the <strong>ensure</strong> clause can be used. <strong>ensure</strong> goes after the last <strong>rescue</strong> clause and contains a chunk of code that will always be executed as the block terminates. The <strong>ensure</strong> block will always run.</p>

                <p>Some common exceptions are:<br /><br /><b>RuntimeError</b> (this is the default exception raised by the raise method), <b>StandardError</b>, <b>NoMethodError</b>, <b>NameError</b>, <b>IOError</b>, <b>TypeError</b> and <b>ArgumentError</b>.

                <p><strong>An Example</strong>: Let's modify program <strong>p027readwrite.rb</strong> to include exception handling as shown in example <strong>p046xreadwrite.rb</strong> below.</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p046xreadwrite.rb
                # Open and read from a text file
                # Note that since a block is given, file will automatically be closed when the block terminates
                begin
                  File.open('p014constructs.rb', 'r') do |f1|
                    while line = f1.gets
                      puts line
                    end
                  end

                  # Create a new file and write to it
                  File.open('test.rb', 'w') do |f2|
                    # use "" for two lines of text
                    f2.puts "Created by Satish\nThank God!"
                  end
                rescue StandardError => msg
                  # display the system generated error message
                  puts msg
                end
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p class="post-note">Improper error messages can provide critical information about an application which may aid an attacker in exploiting the application. The most common problem occurs when detailed internal error messages such as stack traces, database dumps, and error codes are displayed to the user. Security analysts view logging and error handling as potential areas of risk. It is recommended that production applications should not use, for example, a <strong>puts e.backtrace.inspect</strong> call unless it is being directly committed into a log that is not viewable to the end user.</p>

                <h3>Validation example</h3>

                <p>Here's an example from the <em>Ruby Cookbook</em>, showing how one can do validation of user's inputs.</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                class Name
                  # Define default getter methods, but not setter methods.
                  attr_reader :first, :last
                  # When someone tries to set a first name, enforce rules about it.
                  def first=(first)
                    if first == nil or first.size == 0
                      raise ArgumentError.new('Everyone must have a first name.')
                    end
                    first = first.dup
                    first[0] = first[0].chr.capitalize
                    @first = first
                  end

                  # When someone tries to set a last name, enforce rules about it.
                  def last=(last)
                    if last == nil or last.size == 0
                      raise ArgumentError.new('Everyone must have a last name.')
                    end
                    @last = last
                  end

                  def full_name
                    "#{@first} #{@last}"
                  end
                  # Delegate to the setter methods instead of setting the instance
                  # variables directly.
                  def initialize(first, last)
                    self.first = first
                    self.last = last
                  end
                end

                jacob = Name.new('Jacob', 'Berendes')
                jacob.first = 'Mary Sue'
                jacob.full_name # => "Mary Sue Berendes"
                john = Name.new('john', 'von Neumann')
                john.full_name # => "John von Neumann"
                john.first = 'john'
                john.first # => "John"
                john.first = nil
                # ArgumentError: Everyone must have a first name.
                Name.new('Kero, international football star and performance artist', nil)
                # ArgumentError: Everyone must have a last name.
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The Name class keeps track of peoples' first and last names. It uses setter methods to enforce two somewhat parochial rules: everyone must have both a first and a last name, and everyone's first name must begin with a capital letter. The Name class has been written in such a way, that the rules are enforced both in the constructor and after the object has been created. Sometimes you don't trust the data coming in through the setter methods. That's when you can define your own methods to stop bad data before it infects your objects. Within a class, you have direct access to the instance variables. You can simply assign to an instance variable and the setter method won't be triggered. If you do want to trigger the setter method, you'll have to call it explicitly. Note how, in the Name#initialize method above, we call the first= and last= methods instead of assigning to @first and @last. This makes sure the validation code gets run for the initial values of every Name object. We can't just say first = first, because first is a variable name in that method.</p>

                <p style="background-color: #FAFAFA; padding: 5px; margin-top: 20px; font-size: 65%;"><strong>Note</strong>: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various <span style="font-weight: bold;" title="Click Gurus on the menu above">Ruby Gurus</span>), my acknowledgment and thanks to all of them. Much of the material on <a href="/">rubylearning.github.io</a> and in the course at <a href="http://rubylearning.org/">rubylearning.org</a> is drawn <strong>primarily</strong> from the <strong>Programming Ruby book</strong>, available from <a href="http://pragprog.com/book/ruby3/programming-ruby-1-9-2-0">The Pragmatic Bookshelf</a>.</p>

                <p class="post-footer align-right">
                  <strong>
                    <a href="/satishtalim/ruby_access_control.html">&lt;Access Control | </a>
                    <a href="/satishtalim/tutorial.html">TOC | </a>
                    <a href="/satishtalim/ruby_logging.html">Logging &gt;</a>
                  </strong>
                </p>

            </div>
            <!-- main inner ends here -->
        </div>

            <div id="rightbar">
            </div>

    <!-- content-wrap ends here -->
    </div>

<!-- wrap ends here -->
</div>

<!-- footer starts here -->
<div id="footer">
    <!-- CHANGE THE FOOTER -->
    <p>&copy; 2006-2021 <strong>rubylearning.github.io - A Ruby Tutorial</strong>&nbsp;&nbsp;Page Updated: 5th Jan. 2021 | Design: <a href="mailto:ealigam@gmail.com">Erwin Aligam</a> | Valid: <a href="http://validator.w3.org/check/referer">XHTML</a> | <a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="/">Home</a> | <a href="/privacy.html">Privacy</a> | <a href="/sitemap.html">Sitemap</a></p>
</div>

<!-- footer ends here -->

<!-- SyntaxHighlighter code -->
<script src="/js/shCore.js" type="text/javascript"></script>
<script src="/js/shBrushRuby.js" type="text/javascript"></script>
<script type="text/javascript">
dp.SyntaxHighlighter.HighlightAll('code');
</script>
<!-- SyntaxHighlighter code -->
</body>
</html>
